package com.ls.lserp.modules.setting.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.setting.entity.Duty;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.service.DutyService;

import groovy.util.ResourceException;

/**
 * @ClassName: DutyController
 * @Description:
 * 
 * @author 许天航
 * @date 2017年01月09日
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/business/install/")
public class DutyController extends BaseController {

	@Autowired
	private DutyService dutyService;
	
	@ModelAttribute
	public Duty get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return dutyService.findDutyByID(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new Duty();
		}
	}
	

	/**
	 * 查询公司一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String queryDuty(Duty duty, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		return "modules/setting/setDuty";

	}

	/**
	 * 拼接一览画面
	 * @param values 
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("business:install:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Duty duty, HttpServletRequest request, HttpServletResponse response,
			Model model, String[] values) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();
		DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		// ajax回调时使用的一览list名
		request.setAttribute("listNames", "duty");
		// 画面取得的检索项目
		String dutyName = duty.getDutyName();
		String strUri = request.getContextPath() + Global.getAdminPath();

		// 拼接字符串供分页使用
		String searchParam = "&dutyName=" + dutyName;
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<Duty> page = dutyService.findDutyList(new Page<Duty>(request, response),
				duty);
		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//"+ basePath + "templates//demoHtml//dutyList.txt";
		// 读取文件生成字符串
		String dutyHtml = readTxtFile(tempFilePath);
		String createUser = "";
		String strHtml = "";
		int pageNo = 0;
		if (!"".equals(dutyHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				dutyHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				dutyHtml = dutyHtml.replace("pageNo", "" + pageNo);
				// 分类代码
				dutyHtml = dutyHtml.replace("dutyName",
						StringUtils.checkStringNull(page.getList().get(i).getDutyName()));
				String dutyline = "\"popup('800px','519px','" + strUri + "/business/install/viewDuty?dutyID="
						+ page.getList().get(i).getDutyID() + "&editFlag=0')\"";
				// 分类id
				dutyHtml = dutyHtml.replace("dutyId", dutyline);				
				// 分类职务描述
				dutyHtml = dutyHtml.replace("dutyDescribe",
						StringUtils.checkStringNull(page.getList().get(i).getDutyDescribe()));				
				// 分类状态
				String status = page.getList().get(i).getDutyStatus();
				if ("1".equals(status)) {
					status = SystemMessageUtils.getMessageName( "duty_edit_open");
				}else{
					status = SystemMessageUtils.getMessageName( "duty_edit_close");
				}
				dutyHtml = dutyHtml.replace("dutyStatus",
						StringUtils.checkStringNull(status));
				// 创建人
				createUser = StringUtils.checkStringNull(page.getList().get(i).getCreateBy().getFirstName());
				dutyHtml = dutyHtml.replace("createUser", createUser);
				// 创建日期
				dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				Date createDate = page.getList().get(i).getCreateDate();
				dutyHtml = dutyHtml.replace("createDate", dateForamat.format(createDate));
				strHtml += dutyHtml;
			}
		}
		listMap.put("duty", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	/**
	 * 创建职务信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("business:install:view")
	@RequestMapping(value = "createDuty")
	public String createDuty(Duty duty, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		model.addAttribute("duty", duty);
		return "modules/setting/createDuty";

	}

	/**
	 * 编辑职务信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("business:install:view")
	@RequestMapping(value = "editDuty")
	public String editDuty(Duty duty, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String flag = duty.getEditFlag();
		duty = dutyService.findDuty(duty);
		duty.setEditFlag(flag);
		model.addAttribute("duty", duty);
		return "modules/setting/createDuty";

	}
	

	
	
	/**
	 * 保存职务信息
	 * 
	 * @return
	 * @throws duty
	 * @throws ResourceException
	 * @throws  
	 */
	@RequiresPermissions("business:install:edit")
	@ResponseBody
	@RequestMapping(value = "dutySave")
	public String editDutySave(Duty duty,  HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
				if(duty.getDutyID()!=null){
					// 编辑数据
					// 判断数据是否删除
					Duty dutyNew = get(duty.getDutyID().toString());
					// 判断数据是否删除
		            if(dutyNew==null || BaseEntity.DEL_FLAG_DELETE.equals(dutyNew.getDeleteFlag())){
		            	// 返回提示信息
		            	return renderString(response,AjaxDone.error(getText("duty_edit_save_msg_fail")));
		            }
					
		            // 排他处理
				    if(duty.getVersion()==get(duty.getDutyID().toString()).getVersion()){
				    	
				    	// 版本号加1
				    	duty.setVersion(duty.getVersion()+1);
				    }else{
				    	
				    	// 返回提示信息
				    	return renderString(response,AjaxDone.error(getText("duty_edit_save_msg_fail")));
				    }
				}
					
					
				    // 保存数据
					dutyService.saveDuty(duty);
					
					// 保存成功返回提示信息
					return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "duty_edit_save_msg_success")));
					
					
			}
		
		
		
		

	
	
	/**
	 * 删除职务信息
	 * 
	 * @return
	 * @throws duty
	 * @throws ResourceException
	 */
	@RequiresPermissions("business:install:edit")
	@ResponseBody
	@RequestMapping(value = "deleteDuty")
	public String deleteDuty(Duty duty, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		if(duty.getDutyID()!=null){
			// 编辑数据
			// 判断数据是否删除
			Duty dutyNew = get(duty.getDutyID().toString());
			// 判断数据是否删除
            if(dutyNew==null || BaseEntity.DEL_FLAG_DELETE.equals(dutyNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("duty_edit_save_msg_fail")));
            }
			
            // 排他处理
		    if((duty.getVersion()==get(duty.getDutyID().toString()).getVersion())){
		    	
		    	// 版本号加1
		    	duty.setVersion(duty.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(getText("duty_edit_save_msg_fail")));
		    }
		}
			
			
		    // 保存数据
			dutyService.deleteDuty(duty);
			
			// 删除成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "duty_edit_delete_msg_success")));
			

	}
	
	

	/**
	 * 查看一条职务信息
	 * 
	 * @return
	 */
	@RequiresPermissions("business:install:view")
	@RequestMapping(value = "viewDuty")
	public String viewDuty(Duty duty, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String flag = duty.getEditFlag();
		duty = dutyService.findDuty(duty);
		duty.setEditFlag(flag);
		model.addAttribute("duty", duty);
		return "modules/setting/createDuty";

	}
	

	
}